package com.kayang.webapi.service;

import com.kayang.common.config.RedisUtil;
import com.kayang.common.exception.IPException;
import com.kayang.common.exception.ParamException;
import com.kayang.common.misc.WebHelper;
import com.kayang.webapi.config.WebApiConfig;

import com.kayang.nadapt.util.*;
import com.kayang.webapi.tool.MsgCode;
import com.kayang.webapi.tool.MsgContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import java.util.Map;

/**
 * 接口调用前校验用户  客户端IP  参数格式
 */
@Service
public class DataService {
    @Autowired
    DataBizService dataBizService;

    @Autowired
    WebApiConfig webApiConfig;

    @Autowired
    RedisUtil redisUtil;


    public void checkIP(Map<String, Object> param, HttpServletRequest req, int urid)  {
        String curIP = WebHelper.getClientIP(req);
        curIP = StringUtil.isNullOrEmpty(curIP) ? "" : curIP;
        LogHelper.info(req.getServletPath() + " request  ip : " + curIP);
        dataBizService.validateIP(curIP, webApiConfig.getWhiteIPList(), req.getServletPath());

        boolean canCall = dataBizService.checkCallPermission(Convert.toString(param.get("funcId")), urid, curIP);
        if(!canCall){
            throw  new IPException(MsgCode.Code4008, MsgContent.MsgValidateFuncPermission);
        }
    }

    public void checkParams(Map<String, Object> param, HttpServletRequest req) throws ParamException {
        dataBizService.validateVal(req.getServletPath(), param);
    }

    public HashMapIgnoreCase<Object> buildMapIgnoreCase(Map<String, Object> map){
        HashMapIgnoreCase<Object> hashMapIgnoreCase = new HashMapIgnoreCase<>();
        for (String key : map.keySet()) {
            hashMapIgnoreCase.put(key, map.get(key));
        }
        return hashMapIgnoreCase;
    }

}
